const { gzipSync, gunzipSync } = require('zlib');
const { DataTypes } = require('sequelize');

// 假設我們正在建模一個Post，它content是一個長度不受限制的文本。假設要提高內存使用率，我們要存儲內容的壓縮版本。
module.exports = sequelize => sequelize.define(
  'post',
  {
    content: {
      type: DataTypes.TEXT,
      get() {
        const storedValue = this.getDataValue('content');
        const gzippedBuffer = Buffer.from(storedValue, 'base64');
        const unzippedBuffer = gunzipSync(gzippedBuffer);
        return unzippedBuffer.toString();
      },
      set(value) {
        const gzippedBuffer = gzipSync(value);
        this.setDataValue('content', gzippedBuffer.toString('base64'));
      },
    },
  },
  {
    underscored: true,
  },
);
